import { fileURLToPath, URL } from 'node:url'

import { UserConfig, ConfigEnv, loadEnv, defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

// https://vite.dev/config/
export default defineConfig(({ mode, command }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd())

  return {
    base: env.VITE_APP_CONTEXT_PATH,
    plugins: [
      vue(),
      vueJsx(),
      AutoImport({
        dirs: ['./src/hooks', './src/enums'], // 用户模块
        resolvers: [ElementPlusResolver()],
        imports: ['vue', 'vue-router', '@vueuse/core', 'pinia'],
        dts: './types/autoImport.d.ts'
      }),
      createSvgIconsPlugin({
        iconDirs: [fileURLToPath(new URL('src/assets/svg', import.meta.url))],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: command === 'build'
      }),
      Components({
        // 生成自定义 `auto-components.d.ts` 全局声明
        dts: './types/components.d.ts',
        dirs: ['src/components'],
        resolvers: [ElementPlusResolver({ importStyle: 'sass' })]
      }),
      vueDevTools()
    ],
    server: {
      host: '0.0.0.0',
      port: Number(env.VITE_APP_PORT),
      proxy: {
        // 代理标识 环境配置内
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_APP_HOST, // target host 环境配置内
          changeOrigin: true,
          ws: true,
          rewrite: path => path.replace(new RegExp('^' + env.VITE_APP_BASE_API), '')
        }
      }
    },
    resolve: {
      alias: [
        {
          find: '~',
          replacement: fileURLToPath(new URL('./', import.meta.url))
        },
        {
          find: '@',
          replacement: fileURLToPath(new URL('./src', import.meta.url))
        }
      ]
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "~/styles/variables.scss" as *;`
        }
      }
    }
  }
})
